import pandas as pd
import numpy as np
from interpret.glassbox import ExplainableBoostingClassifier
from interpret import show
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.metrics import (
    accuracy_score, f1_score, precision_score,
    recall_score, roc_auc_score, confusion_matrix
)

# ========== 1. 数据读取 ==========
df = pd.read_csv(r"D:\resources\data\jumbo_2020-2021M_0.25deg_ST_SSS_DO_CHL_SSH_MLD_each_year_tertile.csv")

# ========== 2. 特征与标签 ==========
target_col = "Label"
exclude_cols = ['Catch', 'Effort', 'CPUE', 'Label']

feature_cols = [col for col in df.columns if col not in exclude_cols]

# feature_cols = [
#     'ST_0', 'DO_0', 'Year', 'ST_50', 'MLD', 'Month',
#     'SSS_100', 'SSH', 'CHL', 'ST_200', 'ST_150',
#     'Lon', 'ST_500', 'DO_50', 'SSS_150'
# ]

X = df[feature_cols].copy()
y = df[target_col].astype(int)

# ========== 3. 划分训练与测试集 ==========
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# ========== 4. 定义模型与参数网格 ==========
ebm = ExplainableBoostingClassifier(random_state=42)

param_grid = {
    "learning_rate": [0.01, 0.015, 0.02],
    "max_leaves": [2, 3],
    "min_samples_leaf": [2, 4, 5],
    # "max_bins": [256, 512, 1024],
    "smoothing_rounds": [50, 75, 100],
    # "interactions": ['1x', '3x', '5x']  # 控制交互特征数量
}

# ========== 5. 设置网格搜索（10折交叉验证） ==========
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)

grid_search = GridSearchCV(
    estimator=ebm,
    param_grid=param_grid,
    scoring='f1',           # 优化目标指标
    cv=cv,
    n_jobs=-1,              # 并行计算
    verbose=2               # 输出详细过程
)

# ========== 6. 执行网格搜索 ==========
print("\n🔍 正在执行网格搜索，请稍候...")
grid_search.fit(X_train, y_train)

# ========== 7. 输出最优结果 ==========
print("\n✅ 网格搜索完成！")
print(f"最优参数组合：{grid_search.best_params_}")
print(f"最优平均F1-score（交叉验证）: {grid_search.best_score_:.4f}")

# ========== 8. 在测试集上评估最优模型 ==========
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_test)
y_proba = best_model.predict_proba(X_test)[:, 1]

acc = accuracy_score(y_test, y_pred)
prec = precision_score(y_test, y_pred)
rec = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
auc = roc_auc_score(y_test, y_proba)

print("\n🎯 EBM 最优模型在测试集上的评估结果")
print(f"Accuracy  = {acc:.4f}")
print(f"Precision = {prec:.4f}")
print(f"Recall    = {rec:.4f}")
print(f"F1-score  = {f1:.4f}")
print(f"ROC-AUC   = {auc:.4f}")

print("\n混淆矩阵：")
print(confusion_matrix(y_test, y_pred))

# ========== 9. 可解释性展示 ==========
# ebm_global = best_model.explain_global()
# show(ebm_global)
